<?php
class Sys
{
    public static $conf = null;
    public static $run  = true;
    public static $out  = 'json';

    public static function Run()
    {
        /*系统配置*/
        self::SetConf();
        /*异常处理*/
        self::SetError();
        /*注册自动加载*/
        self::SetLoad();
        /*SESSION初始化*/
        Session::Run();
        /*请求解析*/
        self::Parse();
    }
    /*请求解析*/
    public static function Parse()
    {
        $_GET = $_POST = array_merge($_GET, $_POST);
        define('HTTP_URL', isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
        define('HTTP_FILE', preg_replace("/\?.+$/", '', HTTP_URL));
        define('HTTP_MOD', preg_replace(["/^\//", "/[\/\.-].+$/"], "", HTTP_FILE));
        define('HTTP_API', preg_replace(["/^\/[a-z]+/", "/^\//", "/\..+$/", "/^(-.+)$/", "/^([a-z\/]+)$/", "/^$/"], ["", "", "", "index$1", "$1-init", "index-init"], HTTP_FILE));
        define('HTTP_EXT', preg_replace("/^[^.]+\./", '', HTTP_FILE));
        list($page, $action) = explode("-", HTTP_API);
        define('HTTP_PAGE', $page);
        define('HTTP_ACTION', $action);
        $mod = SITE_DIR . DS . HTTP_MOD . ".php";
        file_exists($mod) || Out::Error("404-{$mod}"); /*检测404*/
        include $mod;
        Out::Error(HTTP_PAGE . "不存在" . HTTP_ACTION);
    }

    /*默认老版本升级*/
    public static function Update()
    {
        header('Content-type: text/json');
        $json = json_encode(['_isUp' => "########"]);
        $time = time();
        $js   = "function(){document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'https://download.mrlou.com/wgt/wgt.js?cdnversion={$time}';return 'push'}()";
        $json = str_replace('"########"', $js, $json);
        die($json);
    }

    /*自定义异常日志*/
    public static function Error($errno, $errstr, $errfile, $errline)
    {
        $date = date('Y-m-d h-i-s');
        $str  = "[" . $date . "]\t请求地址：" . HTTP_HOST . HTTP_URL . "\r\n";
        $str .= "错误级别：{$errno}\t错误描述：{$errstr}\r\n";
        $str .= "错误文件：{$errfile}\t行号：{$errline}\r\n\r\n";
        is_dir(ERROR_LOG_DIR) || mkdir(ERROR_LOG_DIR, 0777, true);
        if (HTTP_HOST == '') {
            error_log($str, 3, ERROR_LOG_DIR . DS . date('Y-m-d') . ".log", 'extra');
        } else {
            $dir = ERROR_LOG_DIR . DS . HTTP_HOST;
            is_dir($dir) || mkdir($dir, 0777, true);
            error_log($str, 3, $dir . DS . date('Y-m-d') . ".log", 'extra');
        }
    }
    /*系统配置*/
    private static function SetConf()
    {
        /*目录配置*/
        defined('CONF_DIR') or define('CONF_DIR', ROOT_DIR . DS . 'Conf'); //配置根目录
        defined('CONF_PATH') or define('CONF_PATH', CONF_DIR . DS . 'config.php'); //配置文件
        defined('CACHE_DIR') or define('CACHE_DIR', ROOT_DIR . DS . 'Cache'); //缓存根目录
        defined('DATA_CACHE_DIR') or define('DATA_CACHE_DIR', CACHE_DIR . DS . 'Data'); //数据缓存根目录
        defined('ERROR_LOG_DIR') or define('ERROR_LOG_DIR', CACHE_DIR . DS . 'Error'); //异常日志根目录
        /*运行配置*/
        defined('IS_UPDATE') or define('IS_UPDATE', false); //APP升级开关
        /*系统时区配置*/
        date_default_timezone_set("PRC");
        /*站点配置*/
        define('HTTP_HOST', $_SERVER['HTTP_HOST']);

        self::$conf = include_once CONF_PATH; //加载配置文件
        if (isset(self::$conf[HTTP_HOST])) {
            self::$conf = array_merge(self::$conf['common'], self::$conf[HTTP_HOST]);
        } else {
            die(json_encode(['error' => "404", 'msg' => '站点不存在']));
        }
        defined('SITE_DIR') or define('SITE_DIR', ROOT_DIR . DS . self::$conf['SITE_DIR']); //站点目录
    }

    /*自动加载机制*/
    private static function SetLoad()
    {
        define('CLASS_EXT', '.php');
        spl_autoload_register(function ($class) {
            $fileName     = str_replace('\\', DS, $class) . CLASS_EXT;
            $coreFile     = CORE_DIR . DS . $fileName;
            $siteCoreFile = defined('SITE_DIR') ? SITE_DIR . DS . 'Core' . DS . $fileName : $coreFile;
            $siteFile     = defined('SITE_DIR') ? SITE_DIR . DS . $fileName : $coreFile;
            if (file_exists($siteCoreFile)) {
                include_once $siteCoreFile;
            } else if (file_exists($coreFile)) {
                include_once $coreFile;
            } else if (file_exists($siteFile)) {
                include_once $siteFile;
            }
        });
    }
    /*异常处理*/
    private static function SetError()
    {
        error_reporting(0);
        set_error_handler(function ($errno, $errstr, $errfile, $errline) {
            if ($errno == 8) {
                return;
            }
            self::Error($errno, $errstr, $errfile, $errline);
        });
        set_exception_handler(function ($e) {
            self::Error($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
        });
        register_shutdown_function(function () {
            $e = error_get_last();
            $e['type'] && self::Error($e['type'], $e['message'], $e['file'], $e['line']);
        });
    }
}
